package edu.itcs6112.za.web.controller;

import java.math.BigDecimal;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import edu.itcs6112.za.domain.Address;
import edu.itcs6112.za.domain.Customer;
import edu.itcs6112.za.domain.Item;
import edu.itcs6112.za.domain.Order;
import edu.itcs6112.za.domain.OrderItem;
import edu.itcs6112.za.domain.OrderStatus;
import edu.itcs6112.za.service.CustomerService;
import edu.itcs6112.za.service.ItemService;
import edu.itcs6112.za.service.OrderService;
import edu.itcs6112.za.web.form.CartContents;
import edu.itcs6112.za.web.form.CartItem;
import edu.itcs6112.za.web.form.CustomerOrderModel;
import edu.itcs6112.za.web.form.OrderItemModel;
import edu.itcs6112.za.web.model.ShoppingCart;

@RequestMapping("/cart")

@Controller
public class ShoppingCartController {

	final Logger logger = LoggerFactory.getLogger(ShoppingCartController.class);
	
	//@Autowired
	//private ShoppingCartService shoppingCartService;
	
	@Autowired 
	private ShoppingCart shoppingCart;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ItemService itemService;
	
	@RequestMapping(value = "/addToCart", method = RequestMethod.GET)
	@ResponseBody
	public void addToCart(@RequestParam("id")long itemID){
		Item item = itemService.findById(itemID);
		logger.debug("Adding Item " + item.getName() + " to cart with quantity 1");
		CartItem cartItem = new CartItem();
		cartItem.setItemNumber(item.getId());
		cartItem.setName(item.getName());
		cartItem.setPrice(new BigDecimal(item.getPrice()));
		cartItem.setQuantity(1);
		shoppingCart.addItem(cartItem);
	}
	
	@RequestMapping(value = "/getCart", method = RequestMethod.GET,produces = "application/json")
	@ResponseBody
	public CartContents getCart(){
		CartContents cart = new CartContents();
		cart.setCartContentData(shoppingCart.getItems());
		return cart;
	}
	
	@RequestMapping(value = "/checkSecurity", method = RequestMethod.GET,produces = "application/json")
	@ResponseBody
	public String checkSecurity(Principal principal){
		final String currentUser = principal.getName();
		return currentUser;
	}
	
	@RequestMapping(value = "/removeFromCart", method = RequestMethod.GET)
	@ResponseBody
	public void removeFromCart(@RequestParam("id")long itemID){
		shoppingCart.removeItem(itemID);
	}
	
	
	@RequestMapping(value = "/checkout", method = RequestMethod.POST)
    public String checkout(@Valid CustomerOrderModel customerOrder, BindingResult bindingResult, Model uiModel, 
    		HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes, Locale locale) {
		logger.info("Customer Submitted Order");
		
		//Create and save order object
		Customer cust = customerService.findById(customerOrder.getCustomerId());
		
		Order order = new Order();
		CartContents cart = getCart();
		
		order.setCustomerId(customerOrder.getCustomerId());
		order.setInvoiceNumber("TBD - INVOICE GENERATION");
		
		Address custAddress = new Address();
		custAddress.setAddressLine1(cust.getAddress1());
		custAddress.setAddressLine2(cust.getAddress2());
		custAddress.setCity(cust.getCity());
		custAddress.setState(cust.getState());
		custAddress.setZipCode(cust.getZip());
		custAddress.setCountry("US");
		order.setOrderAddress(custAddress);
		
		order.setOrderDate(DateTime.now());
		order.setOrderTotal(new BigDecimal(cart.getCartTotal()));
		order.setShippingMethod(customerOrder.getShippingMethod());
		order.setStatus(OrderStatus.PendingShipping);
		
		order = orderService.save(order);
		
		logger.debug("New order created with order id {" + order.getOrderNumber() + "}");
		
		//Save the order items now that we have the order ID number set
		List<OrderItem> orderItems = new ArrayList<OrderItem>(); 
				
		for(CartItem cItem : cart.getCartContentData()){
			OrderItem oItem = new OrderItem();
			oItem.setDescription(cItem.getName());
			oItem.setItemId(cItem.getItemNumber());
			oItem.setPrice(cItem.getPrice());
			oItem.setQuantity(cItem.getQuantity());
			
			orderItems.add(oItem);
		}
		
		order.setItems(orderItems);
		
		orderService.save(order);
		
		
		for(OrderItem oItem : order.getItems()){
			logger.debug("New order item created for item id {" + oItem.getItemId() + "}");
		}
		
		uiModel.asMap().clear();
		shoppingCart = new ShoppingCart();

		uiModel.addAttribute("customerOrder", order);
		
		return "cart/confirmation";
    }	
	
	
	@RequestMapping(value = "/checkout", method = RequestMethod.GET)
	public String checkoutForm(Model uiModel, Principal principal){
		final String currentUser = principal.getName();
		
		CustomerOrderModel custOrder = new CustomerOrderModel();
		
		CartContents cart = getCart();
		//Retrieve the customer details from the database
		Customer customer = customerService.findByUsername(currentUser);
		
		custOrder.setCustomerId(customer.getId());
		custOrder.setFirstName(customer.getFirstName());
		custOrder.setLastName(customer.getLastName());

		Address custAddress = new Address();
		custAddress.setAddressLine1(customer.getAddress1());
		custAddress.setAddressLine2(customer.getAddress2());
		custAddress.setCity(customer.getCity());
		custAddress.setState(customer.getState());
		custAddress.setZipCode(customer.getZip());
		custAddress.setCountry("US");
		custOrder.setOrderAddress(custAddress);
		
		custOrder.setOrderDate(DateTime.now());
		
		List<OrderItemModel> orderItems = new ArrayList<OrderItemModel>();
		for(CartItem cItem : cart.getCartContentData()){
			OrderItemModel oItem = new OrderItemModel();
			oItem.setDescription(cItem.getName());
			oItem.setItemId(cItem.getItemNumber());
			oItem.setPrice(cItem.getPrice());
			oItem.setQuantity(cItem.getQuantity());
			
			orderItems.add(oItem);
		}
		
		custOrder.setOrderItems(orderItems);
		
		custOrder.setTotal(new BigDecimal(cart.getCartTotal()));
		
		uiModel.addAttribute("customerOrder", custOrder);
		return "cart/checkout";
	}
	
}
